package czx.wt.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ChenZhiXiang
 * @version 1.0.0
 * @Description TODO
 * @createTime 2018年12月27日 22:44:00
 */
public class SsoClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(SsoClientUtil.class);

    public static final String SERVER_URL_PREFIX = "http://www.server.com:8080";
    public static final String CLIENT01_HOST_URL = "http://www.client01.com:8081";

    /**
     * 当客户端请求被拦截,跳往统一认证中心,需要带redirectUrl的参数,统一认证中心登录后回调的地址
     * 通过Request获取这次请求的地址 http://www.client01.com:8081/client01
     * @param request
     * @return
     */
    public static String getRedirectUrl(HttpServletRequest request){
        logger.info("获取请求URL:"+CLIENT01_HOST_URL+request.getServletPath());
        return CLIENT01_HOST_URL+request.getServletPath();
    }

    /**
     * 根据request获取跳转到统一认证中心的地址 http://www.server.com:8080/checkLogin?redirectUrl=http://www.client01.com:8081/main
     * 通过Response跳转到指定的地址
     * @param request
     * @param response
     * @throws IOException
     */
    public static void redirectToSSOURL(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String redirectUrl = getRedirectUrl(request);
        logger.info("redirectUrl:"+redirectUrl);
        StringBuilder url = new StringBuilder(50);
        url.append(SERVER_URL_PREFIX).append("/checkLogin?redirectUrl=").append(redirectUrl);
        logger.info("重定向到统一中心认证地址："+url.toString());
        response.sendRedirect(url.toString().trim());
    }
}
